<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- CSRF元数据 -->
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <meta name="_csrf_parameter" th:content="${_csrf.parameterName}"/>
    <title>交易记录</title>
    <!-- 使用CDN引入CSS -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/datatables.net-buttons-bs4/2.2.3/buttons.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
    <style>
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 15px 20px;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
        }
        .card-body {
            padding: 20px;
        }
        .status-completed {
            color: #28a745;
            font-weight: bold;
        }
        .status-pending {
            color: #ffc107;
            font-weight: bold;
        }
        .status-cancelled {
            color: #dc3545;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <h2 class="mt-4 mb-4">交易记录</h2>
        
        <div class="card mb-4">
            <div class="card-header">
                <i class="fas fa-search mr-1"></i>查询条件
            </div>
            <div class="card-body">
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="transactionType">交易类型</label>
                            <select id="transactionType" class="form-control">
                                <option value="">全部类型</option>
                                <option value="1">采购入库</option>
                                <option value="2">销售出库</option>
                                <option value="3">库存调拨</option>
                                <option value="4">库存盘点</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="productName">产品名称</label>
                            <input type="text" class="form-control" id="productName" placeholder="输入产品名称">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="warehouseSelect">仓库</label>
                            <select id="warehouseSelect" class="form-control">
                                <option value="">全部仓库</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="transactionStatus">交易状态</label>
                            <select id="transactionStatus" class="form-control">
                                <option value="">全部状态</option>
                                <option value="pending">待处理</option>
                                <option value="processing">处理中</option>
                                <option value="completed">已完成</option>
                                <option value="cancelled">已取消</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="startDate">开始日期</label>
                            <input type="text" class="form-control datepicker" id="startDate" placeholder="选择开始日期">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="endDate">结束日期</label>
                            <input type="text" class="form-control datepicker" id="endDate" placeholder="选择结束日期">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button type="button" class="btn btn-primary btn-block" id="searchBtn">
                                <i class="fas fa-search"></i> 查询
                            </button>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button type="button" class="btn btn-secondary btn-block" id="resetBtn">
                                <i class="fas fa-redo"></i> 重置
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-6">
                        <i class="fas fa-table mr-1"></i>交易记录列表
                    </div>
                    <div class="col-md-6 text-right">
                        <button type="button" class="btn btn-primary btn-sm" id="addBtn">
                            <i class="fas fa-plus"></i> 新增交易
                        </button>
                        <button type="button" class="btn btn-success btn-sm ml-2" id="exportBtn">
                            <i class="fas fa-file-excel"></i> 导出
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="transactionTable" class="table table-bordered" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>交易编号</th>
                                <th>交易类型</th>
                                <th>产品名称</th>
                                <th>数量</th>
                                <th>单位</th>
                                <th>金额</th>
                                <th>仓库</th>
                                <th>交易状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 表格数据将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 交易详情模态框 -->
    <div class="modal fade" id="transactionModal" tabindex="-1" role="dialog" aria-labelledby="transactionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="transactionModalLabel">交易详情</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="transactionDetails">
                        <!-- 交易详情将通过JavaScript动态生成 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 新增/编辑交易模态框 -->
    <div class="modal fade" id="addEditTransactionModal" tabindex="-1" role="dialog" aria-labelledby="addEditTransactionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addEditTransactionModalLabel">新增交易</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="transactionForm">
                        <input type="hidden" id="transactionId" name="transactionId">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalTransactionType">交易类型 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="modalTransactionType" name="modalTransactionType" required>
                                        <option value="">请选择交易类型</option>
                                        <option value="IN">采购入库</option>
                                        <option value="OUT">销售出库</option>
                                        <option value="TRANSFER">库存调拨</option>
                                        <option value="CHECK">库存盘点</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalProductId">产品 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="modalProductId" name="modalProductId" required>
                                        <option value="">请选择产品</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="modalQuantity">数量 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="modalQuantity" name="modalQuantity" required min="0" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="modalUnit">单位 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="modalUnit" name="modalUnit" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="modalAmount">金额 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">¥</span>
                                        </div>
                                        <input type="number" class="form-control" id="modalAmount" name="modalAmount" required min="0" step="0.01">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalWarehouseId">仓库 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="modalWarehouseId" name="modalWarehouseId" required>
                                        <option value="">请选择仓库</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalTargetWarehouseId">目标仓库 <small class="text-muted">(仅调拨交易需要)</small></label>
                                    <select class="form-control" id="modalTargetWarehouseId" name="modalTargetWarehouseId">
                                        <option value="">请选择目标仓库</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalStatus">交易状态 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="modalStatus" name="modalStatus" required>
                                        <option value="PENDING">待处理</option>
                                        <option value="PROCESSING">处理中</option>
                                        <option value="COMPLETED">已完成</option>
                                        <option value="CANCELLED">已取消</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalTransactionDate">交易日期 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control datepicker" id="modalTransactionDate" name="modalTransactionDate" required>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="modalRemark">备注</label>
                            <textarea class="form-control" id="modalRemark" name="modalRemark" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveTransactionBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 使用CDN引入JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/datatables.net-buttons/2.2.3/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/datatables.net-buttons/2.2.3/js/buttons.html5.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
    <script th:src="@{/js/transaction/transaction.js}"></script>
    
    <script>
        $(document).ready(function() {
            // 初始化日期选择器
            $('.datepicker').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                language: 'zh-CN'
            });
            
            // 初始化数据表格
            var table = $('#transactionTable').DataTable({
                language: {
                    "sProcessing": "处理中...",
                    "sLengthMenu": "显示 _MENU_ 项结果",
                    "sZeroRecords": "没有匹配结果",
                    "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                    "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    "sInfoPostFix": "",
                    "sSearch": "搜索:",
                    "sUrl": "",
                    "sEmptyTable": "表中数据为空",
                    "sLoadingRecords": "载入中...",
                    "sInfoThousands": ",",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "上页",
                        "sNext": "下页",
                        "sLast": "末页"
                    }
                },
                // 模拟数据，实际项目中应从后端获取
                data: [
                    ["TX20230601001", "采购入库", "大米", "1000", "kg", "¥5,000.00", "1号仓", "<span class='status-completed'>已完成</span>", "2023-06-01 10:30:00", "<button class='btn btn-sm btn-info view-btn'>查看</button>"],
                    ["TX20230602001", "销售出库", "小麦", "500", "kg", "¥2,500.00", "2号仓", "<span class='status-completed'>已完成</span>", "2023-06-02 14:15:00", "<button class='btn btn-sm btn-info view-btn'>查看</button>"],
                    ["TX20230603001", "库存调拨", "玉米", "800", "kg", "¥3,200.00", "1号仓→3号仓", "<span class='status-pending'>处理中</span>", "2023-06-03 09:45:00", "<button class='btn btn-sm btn-info view-btn'>查看</button>"]
                ],
                columns: [
                    { title: "交易编号" },
                    { title: "交易类型" },
                    { title: "产品名称" },
                    { title: "数量" },
                    { title: "单位" },
                    { title: "金额" },
                    { title: "仓库" },
                    { title: "交易状态" },
                    { title: "创建时间" },
                    { title: "操作" }
                ]
            });
            
            // 查看交易详情
            $('#transactionTable').on('click', '.view-btn', function() {
                var data = table.row($(this).parents('tr')).data();
                
                // 构建交易详情HTML
                var detailsHtml = `
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>交易编号：</strong> ${data[0]}
                        </div>
                        <div class="col-md-6">
                            <strong>交易类型：</strong> ${data[1]}
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>产品名称：</strong> ${data[2]}
                        </div>
                        <div class="col-md-6">
                            <strong>数量：</strong> ${data[3]} ${data[4]}
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>金额：</strong> ${data[5]}
                        </div>
                        <div class="col-md-6">
                            <strong>仓库：</strong> ${data[6]}
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>交易状态：</strong> ${data[7]}
                        </div>
                        <div class="col-md-6">
                            <strong>创建时间：</strong> ${data[8]}
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <strong>交易备注：</strong>
                            <p>这是一条交易备注信息，描述交易的相关详情。</p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <strong>交易流程：</strong>
                            <ul class="list-group">
                                <li class="list-group-item">2023-06-01 10:30:00 - 创建交易</li>
                                <li class="list-group-item">2023-06-01 11:15:00 - 审核通过</li>
                                <li class="list-group-item">2023-06-01 14:20:00 - 完成交易</li>
                            </ul>
                        </div>
                    </div>
                `;
                
                $('#transactionDetails').html(detailsHtml);
                $('#transactionModal').modal('show');
            });
            
            // 查询按钮点击事件
            $('#searchBtn').click(function() {
                // 实际项目中应根据查询条件从后端获取数据
                alert('查询功能将根据实际后端接口实现');
            });
            
            // 重置按钮点击事件
            $('#resetBtn').click(function() {
                $('#transactionType').val('');
                $('#productName').val('');
                $('#warehouseSelect').val('');
                $('#transactionStatus').val('');
                $('#startDate').val('');
                $('#endDate').val('');
            });
            
            // 新增交易按钮点击事件
            $('#addBtn').click(function() {
                // 重置表单
                $('#transactionForm')[0].reset();
                $('#transactionId').val('');
                
                // 初始化日期为今天
                $('#modalTransactionDate').datepicker('setDate', new Date());
                
                // 显示模态框
                $('#addEditTransactionModalLabel').text('新增交易');
                $('#addEditTransactionModal').modal('show');
                
                // 根据交易类型显示/隐藏目标仓库
                $('#modalTransactionType').change();
            });
            
            // 交易类型变化时显示/隐藏目标仓库
            $('#modalTransactionType').change(function() {
                if ($(this).val() === 'TRANSFER') {
                    $('#modalTargetWarehouseId').closest('.col-md-6').show();
                } else {
                    $('#modalTargetWarehouseId').closest('.col-md-6').hide();
                }
            });
            
            // 保存交易按钮点击事件
            $('#saveTransactionBtn').click(function() {
                // 表单验证
                if (!$('#transactionForm')[0].checkValidity()) {
                    $('#transactionForm')[0].reportValidity();
                    return;
                }
                
                // 收集表单数据
                var formData = {
                    transactionType: $('#modalTransactionType').val(),
                    productId: parseInt($('#modalProductId').val(), 10), // 确保转换为数值类型
                    productName: $('#modalProductId option:selected').text(),
                    quantity: $('#modalQuantity').val(),
                    unit: $('#modalUnit').val(),
                    amount: $('#modalAmount').val(),
                    warehouseId: parseInt($('#modalWarehouseId').val(), 10), // 确保转换为数值类型
                    warehouseName: $('#modalWarehouseId option:selected').text(),
                    status: $('#modalStatus').val(),
                    remark: $('#modalRemark').val()
                };
                
                // 如果是编辑，添加ID
                var transactionId = $('#transactionId').val();
                if (transactionId) {
                    formData.transactionId = parseInt(transactionId, 10); // 确保转换为数值类型
                }
                
                // 获取CSRF令牌
                var token = $("meta[name='_csrf']").attr("content");
                var header = $("meta[name='_csrf_header']").attr("content");
                
                // 发送请求保存交易
                $.ajax({
                    url: '/api/transaction/save',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    beforeSend: function(xhr) {
                        // 添加CSRF令牌到请求头
                        if (token && header) {
                            xhr.setRequestHeader(header, token);
                        }
                    },
                    success: function(res) {
                        if (res.code === 200) {
                            alert(transactionId ? '更新成功' : '添加成功');
                            $('#addEditTransactionModal').modal('hide');
                            // 刷新表格
                            location.reload();
                        } else {
                            alert((transactionId ? '更新' : '添加') + '失败：' + res.message);
                        }
                    },
                    error: function(xhr) {
                        alert((transactionId ? '更新' : '添加') + '失败：' + xhr.responseText);
                    }
                });
            });
            
            // 导出按钮点击事件
            $('#exportBtn').click(function() {
                alert('导出功能将根据实际需求实现');
            });
            
            // 加载仓库下拉框选项
            $.ajax({
                url: '/api/transaction/warehouses',
                type: 'GET',
                success: function(res) {
                    if (res && res.code === 200 && res.data) {
                        var options = '';
                        $.each(res.data, function(index, warehouse) {
                            options += '<option value="' + warehouse.id + '">' + warehouse.name + '</option>';
                        });
                        $('#warehouseSelect').html('<option value="">全部仓库</option>' + options);
                        $('#modalWarehouseId').html('<option value="">请选择仓库</option>' + options);
                        $('#modalTargetWarehouseId').html('<option value="">请选择目标仓库</option>' + options);
                    }
                },
                error: function() {
                    console.log('加载仓库列表失败');
                }
            });
            
            // 加载产品下拉框选项
            $.ajax({
                url: '/api/transaction/products',
                type: 'GET',
                success: function(res) {
                    if (res && res.code === 200 && res.data) {
                        var options = '';
                        $.each(res.data, function(index, product) {
                            options += '<option value="' + product.id + '">' + product.name + '</option>';
                        });
                        $('#modalProductId').html('<option value="">请选择产品</option>' + options);
                    }
                },
                error: function() {
                    console.log('加载产品列表失败');
                }
            });
            
            // 产品选择变更时自动填充单位
            $('#modalProductId').change(function() {
                var productId = $(this).val();
                if (!productId) {
                    $('#modalUnit').val('');
                    return;
                }
                
                $.ajax({
                    url: '/api/transaction/product/' + productId,
                    type: 'GET',
                    success: function(res) {
                        if (res.code === 200) {
                            $('#modalUnit').val(res.data.unit);
                        }
                    }
                });
            });
        });
    </script>
</body>
</html> 